﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DABLL;
using DADAL;
using Microsoft.IdentityModel.Tokens;

namespace DataAcquisition
{
    public partial class DeviceAddForm : BaseForm
    {
        #region 属性


        #endregion

        #region 自定义方法
        /// <summary>重载
        /// 
        /// </summary>
        private void Reload()
        {
            DeviceNumberInput.Text = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
        }

        /// <summary>
        /// 数据错误
        /// </summary>
        /// <param name="msg"></param>
        private void DataError(string msg) 
        {
            Error(msg);
            return;
        }

        #endregion

        #region 系统方法
        public DeviceAddForm()
        {
            InitializeComponent();
            Header.Text = "设备添加";
        }

        private void DeviceAddForm_Load(object sender, EventArgs e)
        {
            DeviceNumberInput.Text = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
        }
        #endregion

        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            DeviceModel model = new DeviceModel();
            try
            {
                model.Number = Convert.ToInt32(DeviceNumberInput.Text);
            }
            catch (Exception)
            {
                Reload();
                Error("设备编号错误，请重新添加");
                return;
            }

            if (DeviceNameInput.Text.IsNullOrEmpty())
            {
                Error("请输入设备名称");
                return;
            }
            model.Name = DeviceNameInput.Text;

            if (SlaveAddressInput.Text.IsNullOrEmpty())
            {
                Error("请输入设备地址");
                return;
            }
            model.SlaveAddress = SlaveAddressInput.Text;

            if (PortSelect.Text.IsNullOrEmpty())
            {
                Error("请选择串口地址");
                return;
            }
            model.PortAddress = PortSelect.Text;

            if (BaudrateSelect.Text.IsNullOrEmpty())
            {
                Error("请选择波特率");
                return;
            }
            model.Baudrate = Convert.ToInt16(BaudrateSelect.Text);

            Response response = Device.AddDevice(model);
            if (response.Code != 200)
            {
                Error(response.Msg);
                return;
            }
            else
            {
                this.Close();
                if (this.Owner is not null)
                {
                    DeviceManageForm frm = (DeviceManageForm)this.Owner;
                    frm.Success(response.Msg);
                    frm.LoadList();
                }
            }
        }
    }
}
